//
//  EditTraining.swift
//  Fitness
//
//  Created by duanwenpu on 2021/9/9.
//

import SwiftUI

enum WeekDay: String, CaseIterable, Identifiable {
    case Monday = "星期一"
    case Tuesday = "星期二"
    case Wednesday = "星期三"
    case Thursday = "星期四"
    case Friday = "星期五"
    case Saturday = "星期六"
    case Sunday = "星期日"
    
//    var chinese: String {
//        switch self {
//        case .Monday:
//            return "星期一"
//        case .Tuesday:
//            return "星期二"
//        case .Wednesday:
//            return "星期三"
//        case .Thursday:
//            return "星期四"
//        case .Friday:
//            return "星期五"
//        case .Saturday:
//            return "星期六"
//        case .Sunday:
//            return "星期日"
//        default:
//            return ""
//        }
//
//    }
    

    
    var id: String { self.rawValue }
}


struct EditTrainingContentView: View {
    var currentTitle: String = ""
    @Binding var handledWeekTraining: Array <EveryDayTrainingModel>
    @State var edit: Bool
    @State private var username: String = ""
    @State private var isEditing = false
    @State private var showActionSheet = false
//    @State private var weekSelectedString: String = "请选择"
//    @State private var weekDayArray: Array = ["星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日", ]
    @State private var selectedDay = WeekDay.Monday.rawValue
    @State private var showWeekPicker: Bool = false
    @State var presentingModal = false
    @State var currentDayTraining: EveryDayTrainingModel
    @State private var inputGroupName: String = ""
    @State private var playTitle: String = "播放"
    @State private var showingAlert = false
    @State private var showingAlertString = "提示"

    @Binding var pushActive: Bool
    func addEmptyGroup() {
        if !inputGroupName.isEmpty {
//            var groupModel = TrainingGroupModel(id: currentDayTraining.trainingGroupArray.count, whatDay: selectedDay, groupName: inputGroupName, trainingArray: [])
            currentDayTraining.trainingGroupArray.append(TrainingGroupModel(id: (currentDayTraining.trainingGroupArray.count + 1), whatDay: selectedDay, groupName: inputGroupName, trainingArray: []))
            var groupModel = currentDayTraining.trainingGroupArray[0]
            withUnsafePointer(to: &groupModel) {ptr in print("====\(ptr)")}
        }
    }
    
    func addEmptyActionRow(_ index: Int) {
        let tempIndex = index - 1;
        if tempIndex < currentDayTraining.trainingGroupArray.count {
            var groupModel = currentDayTraining.trainingGroupArray[tempIndex]
//            withUnsafePointer(to: &groupModel) {ptr in print("====\(ptr)")}
            groupModel.trainingArray.append(TrainingModel(id: (groupModel.trainingArray.count + 1), actionName: "请输入", actionTimes: "0", perWeight: "0", restTime: "0"))
            currentDayTraining.trainingGroupArray[tempIndex] = groupModel
            
        }
//        self.trainingGroup.trainingArray.append(TrainingModel(id: 2, actionName: "请输入", actionTimes: "0", perWeight: "0", restTime: "0"))
    }
    func changeActionRow(_ actionTime: String, _ perWeight: String, _ resetTime: String, _ index: Int, _ groupId: Int) -> Void {
        let tempGroupId = groupId - 1;
        let tempIndex = index - 1;
        if tempGroupId < currentDayTraining.trainingGroupArray.count {
            var groupModel = currentDayTraining.trainingGroupArray[tempGroupId]
            if tempIndex < groupModel.trainingArray.count {
                var trainingModel = groupModel.trainingArray[tempIndex]
                trainingModel.actionTimes = actionTime
                trainingModel.perWeight = perWeight
                trainingModel.actionName = groupModel.groupName
                trainingModel.restTime = resetTime
                groupModel.trainingArray[tempIndex] = trainingModel
            }
            currentDayTraining.trainingGroupArray[tempGroupId] = groupModel
        }
    }
    var body: some View {
        
        VStack(
            alignment: .leading
        ) {
            HStack(
                alignment: .center, spacing: 20
            ) {
                Spacer()
                Text("请选择星期")
                Button(action: {
                    showWeekPicker = true
                }, label: {
                    Text("\(selectedDay)")
                })
                .disabled(!edit)
                Spacer()
            }
            .border(Color.yellow, width: 2)
            HStack(
                alignment: .center, spacing: 20
            ) {
                TextField(
                    "输入组名称",
                    text: $inputGroupName
                )
                .disabled(!edit)

                Button(action: {
                    
                    addEmptyGroup()
                }, label: {
                    Text("增加组")
                })
                    .disabled(!edit)
            }
            List {
                ForEach(currentDayTraining.trainingGroupArray) {trainingGroup in
                    Section(header: TrainingGroupRow(trainingGroup: trainingGroup, edit: edit, addActionCallBack: {(index) -> () in
                        addEmptyActionRow(index)
                    })) {
                        ForEach(trainingGroup.trainingArray) {trainingModel in
                            TrainingActionRow(trainingModel: trainingModel, edit: edit, confirmBlock: {(action, weight, resetTime, index) -> () in
                                changeActionRow(action, weight, resetTime, index, trainingGroup.id)
                                
                            })
                        }
                    }
                }
            }
            if !edit {
                HStack(alignment: .center, spacing: 20) {
                    Spacer()
                    Button(action: {
                        self.playTitle = "播放"
                        voiceManager.playWithModel(currentDayModel: self.currentDayTraining)
                        
                    }, label: {
                        Text("\(self.playTitle)")
                            .font(.system(size: 24, weight: .medium, design: .default))
                    })
                    Button(action: {
                        self.playTitle = "继续"
//                        voiceManager.playWithModel(currentDayModel: self.currentDayTraining)
                        voiceManager.suspendSpeech()
                        
                    }, label: {
                        Text("暂停")
                            .font(.system(size: 24, weight: .medium, design: .default))
                    })
                    Button(action: {
                        voiceManager.stopSpeech()
                    }, label: {
                        Text("结束")
                            .font(.system(size: 24, weight: .medium, design: .default))
                    })
                    Spacer()
                }

            }
            Spacer()
            if self.showWeekPicker {
                Button(action: {
                    showWeekPicker = false
                    currentDayTraining.whatDay = selectedDay
                }, label: {
                    Text("确认")
                })
                Picker("星期", selection: $selectedDay) {
                    ForEach(WeekDay.allCases) {day in
                        Text(day.rawValue)
                    }
                }
            }
        }
        .navigationTitle(currentTitle)
        .navigationBarItems(trailing: edit ? Button(action: {
            self.handledWeekTraining.append(self.currentDayTraining)
//            print(self.handledWeekTraining)
//            save("WeakTraining.json", self.handledWeekTraining)
//            self.handledWeekTraining =
//            saveSql(self.currentDayTraining)
            saveSql(self.currentDayTraining) { v1 in
                self.showingAlertString = v1
                self.showingAlert = true
            }
            pushActive = false
        }, label: {
            Text("保存")
        }) : nil).alert(isPresented:$showingAlert) {
            Alert(title: Text("提示").font(.title), message: Text(self.showingAlertString).font(.body), dismissButton: .default(Text("好的")) {
            })
        }
    }

}



//struct EditTraining_Previews: PreviewProvider {
//    static var previews: some View {
//        EditTrainingContentView(currentTitle: "", handledWeekTraining: .constant([]),edit: true, currentDayTraining: EveryDayTrainingModel(id: 0, whatDay: "星期一", trainingGroupArray: []), pushActive: .constant(true))
//    }
//}
